package com.wmh.baseservice.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdInfo;
import com.wmh.baseservice.admin.pojo.AdMenu;
import com.wmh.baseservice.admin.pojo.AdRoleMenu;
import com.wmh.baseservice.admin.pojo.AdRolePermissions;
import com.wmh.baseservice.admin.service.AdRoleMenuService;
import com.wmh.baseservice.admin.tools.enums.AdMenuFlag;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wmh.baseservice.admin.service.AdRolePermissionsService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mmx generator
 * @since 2021-10-29
 */
@Api(tags = "管理员-角色权限相关接口")
@RestController
@RequestMapping(value = "admin/adRolePermissions", produces = "text/plain;charset=utf-8")
@RequiresRoles("admin")
public class AdRolePermissionsController {

    @Resource
    private AdRolePermissionsService adRolePermissionsService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private AdRoleMenuService adRoleMenuService;

    @ApiOperation("列表(无分页)")
    @PostMapping("listNoPage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String listNoPage(Long id) {
        JSONObject jsonObject = new JSONObject(true);
        List<AdRolePermissions> list = adRolePermissionsService.list(new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, 2).isNull(AdRolePermissions.AD_ID));
        List<String> listCheck = adRolePermissionsService.list(new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, 2).eq(AdRolePermissions.AD_ID, id)).stream().map(AdRolePermissions::getPermissions).collect(Collectors.toList());
        jsonObject.put("list", list);
        jsonObject.put("listCheck", listCheck);
        return ReturnBody.success(jsonObject);
    }

    @ApiOperation("列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "type")
    public String list(PageInfo pageInfo, Integer type) {
        pageInfo.setTimeScreen(AdRolePermissions.CREATE_TIME);
        pageInfo.setDefaultSort(AdRolePermissions.CREATE_TIME, SortWay.DESC);
        //执行分页辅助工具
        PageResult<AdRolePermissions> pageResult = new PageUtil<AdRolePermissions>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.isNull(AdRolePermissions.AD_ID);
            queryWrapper.eq(AdRolePermissions.TYPE, type);
            queryWrapper.ne(AdRolePermissions.ID,1);
            adRolePermissionsService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("分配权限")
    @PostMapping("setPer")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String setPer(Long id, String rolePerId) {
        List<AdRolePermissions> adRolePermissionList = new ArrayList<>();
        List<String> rolePerLongId = JSON.parseArray(rolePerId, String.class);
        rolePerLongId.forEach(item -> {
            AdRolePermissions adRolePermissions = new AdRolePermissions();
            adRolePermissions.setAdId(id).setPermissions(item).setType(2);
            adRolePermissionList.add(adRolePermissions);
        });
        adRolePermissionsService.setPer(id, adRolePermissionList);
        return ReturnBody.success();
    }

    @ApiOperation("添加角色/权限")
    @PostMapping("add")
    public String add(String name, String remark, Integer type) {
        AdRolePermissions adRolePermissions = adRolePermissionsService.getOneForUpdate(type == 1 ? new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, type).eq(AdRolePermissions.ROLE, name).isNull(AdRolePermissions.AD_ID)
                : new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, type).eq(AdRolePermissions.ROLE, name).isNull(AdRolePermissions.AD_ID));
        if (CommUtil.checkNull(adRolePermissions)) {
            return ReturnBody.error("该角色/权限已存在");
        }
        adRolePermissions=new AdRolePermissions();
        if (type == 1) {
            adRolePermissions.setRole(name);
        } else {
            adRolePermissions.setPermissions(name);
        }
        adRolePermissions.setRemark(remark);
        adRolePermissions.setType(type);
        if (!adRolePermissionsService.save(adRolePermissions)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("修改角色/权限")
    @PostMapping("update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String update(Long id, String name, String remark, Integer type) {
        AdRolePermissions adRolePermissions;
        adRolePermissions = adRolePermissionsService.getOneForUpdate(type == 1 ? new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, type).eq(AdRolePermissions.ROLE, name).isNull(AdRolePermissions.AD_ID)
                : new QueryWrapper<AdRolePermissions>().eq(AdRolePermissions.TYPE, type).eq(AdRolePermissions.ROLE, name).isNull(AdRolePermissions.AD_ID));
        if (CommUtil.checkNull(adRolePermissions) && !adRolePermissions.getId().equals(id)) {
            return ReturnBody.error("该角色/权限已存在");
        }
        AdRolePermissions raw = adRolePermissionsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(raw)) {

            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        adRolePermissions = new AdRolePermissions();
        adRolePermissions.setId(id);
        if (type == 1) {
            adRolePermissions.setRole(name);
        } else {
            adRolePermissions.setPermissions(name);
        }
        adRolePermissions.setRemark(remark);
        adRolePermissions.setType(type);
        adRolePermissionsService.updateInfo(adRolePermissions, type == 1 ? raw.getRole() : raw.getPermissions());
        return ReturnBody.success();
    }

    @ApiOperation("删除")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String delete(Long id, Integer type) {
        adRolePermissionsService.delete(id, type);
        return ReturnBody.success();
    }

    @ApiOperation("分配菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer[].class, name = "menuIds", value = "菜单ID数组", required = true)
    })
    @PostMapping("setRoleMenu")
    @ParameterVerify(notNull = {"roleId"})
    public String setRoleMenu(Long roleId, Long[] menuIds) {
        if (menuIds == null) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (menuIds.length < 1) {
            return ReturnBody.error("请选择菜单");
        }
        Long id = (Long) request.getAttribute(AdInfo.ID);
        if (id != 1) {
            return ReturnBody.error("操作该接口的权限不足");
        }
        return adRoleMenuService.setRoleMenu(roleId, menuIds);
    }

    @ApiOperation("获取该角色拥有的菜单权限")
    @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "id", value = "角色ID", required = true)
    @PostMapping("getRoleMenuId")
    public String getRoleMenuId(Long roleId) {
        if (!CommUtil.checkNull(roleId)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        AdRoleMenu adminRoleMenu = new AdRoleMenu();
        adminRoleMenu.setRoleId(roleId);
        List<AdMenu> list = adRoleMenuService.selectRoleMenu(adminRoleMenu);
        List<Long> integers = new ArrayList<>();
        list.stream()
                .filter(item -> item.getFlag().equals(AdMenuFlag.INTERFACE.getValue()))
                .collect(Collectors.toList())
                .forEach(item -> integers.add(item.getId()));
        return ReturnBody.success(integers);
    }


}
